#-*- coding:UTF-8 -*-

import httplib
import MySQLdb
import sys 
import time
import Config
import util

def getlog():
    import logging
    logger = logging.getLogger()
    hdlr = logging.FileHandler("log.log")
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(logging.NOTSET)
    return logger


db=MySQLdb.connect(host=Config.DBHOST,
                   user=Config.DBUSER,passwd=Config.DBPASS,db=Config.DB,
                   connect_timeout=3600,charset="utf8",use_unicode=True)


def UploadImage(albumid,album):
    logger=getlog()
    cur=db.cursor()
    host=Config.HOST
    cur.execute("SELECT image,id FROM picture WHERE  albumid=%s",albumid)
    rs=cur.fetchall()
    header={"Content-Type":"application/x-www-form-urlencoded"}
    i=0
    for r in rs:
        i+=1
        retry=True
        while retry:
            retry=False
            try:
                resp=util.post_multipart(host,"/pic/store",[("albumid",str(album))],[("img","tmp",r[0])])
                print i," ",resp.status," ",resp.read()
                if resp.status!=200:
                    logger.error("status 502: %s"%r[1])
            except Exception,e:
                print "Exception: ",e
                logger.error("Exception: %s"%r[1])
                retry=True
                time.sleep(30)

if __name__=="__main__":
    begtime=time.time()
    UploadImage(51,99)
    print time.time()-begtime